import React, { Component } from 'react'
import {
  StyleSheet,
  View,
  FlatList,
  Text,
  Modal,
  TextInput,
  TouchableOpacity,
  NativeAppEventEmitter,
  DeviceEventEmitter,
  AsyncStorage,
} from 'react-native'

import Base from './Base'
import {
  isIos,
  NavigationActions,
  createAction,
  getBorderWidth,
  setAsyncStorage,
  getAsyncStorage,
} from '../utils'

import Icon from 'react-native-vector-icons/Ionicons'
import AMapLocation from 'react-native-amap-location'
import MessageModal from '../component/MessageModal'
import SystemSetting from 'react-native-system-setting'
import Empty from '../component/Empty'
import { toast } from '../utils/toast'
import Button from '../component/Button'
import RootView from '../component/RootView'
import SearchInput from '../component/SearchInput'
import * as villageService from '../services/village'

const borderWidth = getBorderWidth()

class CloseButton extends Component {
  render() {
    return (
      <TouchableOpacity onPress={() => this.props.onPress()}>
        <View
          style={{ flex: 1, justifyContent: 'center', paddingHorizontal: 16 }}
        >
          <Icon name="ios-close" size={36} />
        </View>
      </TouchableOpacity>
    )
  }
}

class Village extends Base {
  constructor(props) {
    super(props)
    this.state = {
      location: '',
      data: {},
      modalVisible: false,
      modalType: '',
    }
    this.subscription = null
  }
  loadLocation() {
    SystemSetting.isLocationEnabled().then(enable => {
      if (!enable) {
        this.setState({
          modalVisible: true,
          modalType: 'message',
        })
      } else {
        this.loadAMap()
      }
    })
  }
  loadAMap() {
    this.setState({ fetching: true })
    AMapLocation.init(null)
    AMapLocation.getReGeocode()
  }
  onLocationResult(result) {
    // 缓存经纬度
    if (result.coordinate) {
      const longitude = result.coordinate.longitude
      const latitude = result.coordinate.latitude

      setAsyncStorage('COORDINATE', `${longitude}#${latitude}`).then(data => {
        this.loadData(longitude, latitude)
      })
      return
    }
    // 位置获取失败
    this.setState({
      fetching: false,
      modalVisible: true,
      modalType: 'message',
    })
  }
  loadData(lng = '', lat = '', keyword = '') {
    this.setState({ fetching: true })
    const params = { keyword }
    if (lng) {
      params.lng = lng
    }
    if (lat) {
      params.lat = lat
    }
    villageService
      .list(params)
      .then(data => {
        if (data.total == 0 && lng && lat) {
          this.setState({
            fetching: false,
            modalVisible: true,
            modalType: 'location',
          })
          return
        }
        this.setState({ data, fetching: false })
      })
      .catch(e => {
        this.checkError(e)
      })
  }

  onItemPress(item) {
    const { params } = this.props.navigation.state
    if (params && params.key) {
      DeviceEventEmitter.emit('address.location', {
        id: item.id,
        name: item.name,
        province: item.province,
        city: item.city,
        district: item.district,
      })
    } else {
      DeviceEventEmitter.emit('location.reload', {
        id: item.id,
        name: item.name,
        province: item.province,
        city: item.city,
        district: item.district,
      })
    }

    this.goBack()
  }
  onBack() {
    // DeviceEventEmitter.emit('location.reload', null)
    this.goBack()
  }

  renderHeader() {
    const { params } = this.props.navigation.state
    return (
      <View style={{ height: isIos() ? 64 : 64, backgroundColor: 'white' }}>
        <View
          style={{
            marginTop: isIos() ? 20 : 0,
            flex: 1,
            paddingHorizontal: 16,
            flexDirection: 'row',
            alignItems: 'center',
            justifyContent: 'center',
          }}
        >
          <TouchableOpacity
            onPress={() => this.onBack()}
            style={{ width: 36, justifyContent: 'center' }}
          >
            <Icon name="ios-close" size={36} style={{ color: '#333' }} />
          </TouchableOpacity>

          <View
            style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}
          >
            <Text numberOfLines={1}  style={{fontSize:16,fontWeight:'bold'}}>选择小区</Text>
          </View>
          <View style={{ width: 36 }} />
        </View>
      </View>
    )
  }

  renderItem = ({ item, index }) => {
    let borderTopWidth = borderWidth
    if (index == 0) {
      borderTopWidth = 0
    }
    return (
      <TouchableOpacity
        activeOpacity={0.85}
        onPress={() => this.onItemPress(item)}
      >
        <View style={[styles.item, { borderTopWidth }]}>
          <Text>{item.name}</Text>
        </View>
      </TouchableOpacity>
    )
  }
  closeModal() {
    this.setState({ modalType: '', modalVisible: false })
  }
  renderModal() {
    const { modalType, modalVisible, locationFromVillage } = this.state

    if (modalType == 'message') {
      return (
        <MessageModal
          title="温馨提示"
          action={[
            <TouchableOpacity
              key="k1"
              style={{
                flex: 1,
                alignItems: 'center',
                paddingHorizontal: 16,
                paddingVertical: 12,
              }}
              onPress={() => {
                this.closeModal()
                this.loadData(null,null,'')
              }}
            >
              <Text style={{ color: '#0398ff' }}>确定</Text>
            </TouchableOpacity>,
            <TouchableOpacity
              key="k2"
              style={{
                flex: 1,
                alignItems: 'center',
                paddingHorizontal: 16,
                paddingVertical: 12,
              }}
              onPress={() => {
                this.closeModal()
                SystemSetting.switchLocation(() => {})
              }}
            >
              <Text style={{ color: '#0398ff' }}>开启定位</Text>
            </TouchableOpacity>,
          ]}
        >
          <Text>未能获取到您的地理位置，请开启定位或直接搜索小区</Text>
        </MessageModal>
      )
    }

    if (modalType == 'location') {
      return (
        <MessageModal
          title="温馨提示"
          action={[
            <TouchableOpacity
              key="k1"
              style={{
                flex: 1,
                alignItems: 'center',
                paddingHorizontal: 16,
                paddingVertical: 12,
              }}
              onPress={() => {
                this.closeModal()
                this.loadData(null,null,'')
              }}
            >
              <Text style={{ color: '#0398ff' }}>确定</Text>
            </TouchableOpacity>,
          ]}
        >
          <Text>当前位置不在服务范围内，您可以尝试手动输入小区名称进行搜索</Text>
        </MessageModal>
      )
    }
  }
  componentWillUnmount() {
    this.subscription.remove()
  }
  componentDidMount() {
    this.subscription = NativeAppEventEmitter.addListener(
      'amap.location.onLocationResult',
      data => this.onLocationResult(data)
    )

    getAsyncStorage('COORDINATE')
      .then(data => {
        const d = data.split('#')
        this.loadData(d[0], d[1])
      })
      .catch(e => {
        this.loadLocation()
      })
  }

  render() {
    const { fetching, location, data } = this.state

    let size = 1
    if (data.records) {
      size = data.records.length
    }
    return (
      <RootView fetching={fetching} style={styles.container}>
        {this.renderHeader()}
        <View style={{ paddingHorizontal: 16, paddingBottom: 10 }}>
          <SearchInput
            placeholder="请输入小区名称"
            onChangeText={keyword => {
              if (keyword.trim() != '') {
                this.loadData(null, null, keyword)
              }
            }}
          />
        </View>
        <View style={{ backgroundColor: '#f9f9f9', flex: 1 }}>
          <View
            style={{
              paddingHorizontal: 16,
              marginTop: 15,
              justifyContent: 'space-between',
              flexDirection: 'row',
            }}
          >
            <Text style={{ fontSize: 12, color: '#888' }}>附近小区</Text>

            <TouchableOpacity
              style={{ flexDirection: 'row', alignItems: 'center' }}
              onPress={() => this.loadLocation()}
            >
              <Icon name={'ios-locate-outline'} size={14} color="#0096ff" />
              <Text style={{ color: '#0096ff', fontSize: 12, marginLeft: 5 }}>
                重新定位
              </Text>
            </TouchableOpacity>
          </View>

          {size > 0 ? (
            <FlatList
              style={{ flex: 1, marginTop: 15 }}
              horizontal={false}
              keyExtractor={(item, index) => String(index)}
              data={data.records}
              renderItem={this.renderItem}
            />
          ) : (
            <Empty />
          )}
        </View>
        <Modal
          animationType={'fade'}
          transparent
          onRequestClose={() => {}}
          visible={this.state.modalVisible}
        >
          {this.renderModal()}
        </Modal>
      </RootView>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'white',
  },
  item: {
    backgroundColor: 'white',
    paddingHorizontal: 16,
    paddingVertical: 12,

    borderTopColor: '#e5e5e5',
  },
})

export default Village
